package com.qyy.remotemonitor;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;

import com.blankj.utilcode.util.LogUtils;
import com.qyy.remotemonitor.ui.service.RemoteMonitorService;

import java.util.List;

import static android.app.job.JobInfo.NETWORK_TYPE_ANY;

/**
 * Created by qinyy on 2018/5/14.
 */

@SuppressLint({"NewApi", "Registered"})
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyJobService extends android.app.job.JobService
{
    int startId = 1;
    private JobScheduler mJobScheduler;

    @Override
    public boolean onStartJob(JobParameters params)
    {
        LogUtils.dTag("JobService","onStartJob");
        doJob();
        return true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.dTag("JobService","onStartCommand");
        doJob();
        initSchedule();
        return START_STICKY;
    }

    private void initSchedule()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            if(startId > 65534)
                startId = 1;
            JobInfo.Builder builder = new JobInfo.Builder((int) startId++,
                    new ComponentName(getPackageName(), MyJobService.class.getName()));

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS); //执行的最小延迟时间
                builder.setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);  //执行的最长延时时间
                builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);//线性重试方案
            } else {
                // 每周期执行
                builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
                builder.setRequiresDeviceIdle(true);
            }
            // 执行时的网络状态为任何网络状态
            builder.setRequiredNetworkType(NETWORK_TYPE_ANY);
            builder.setPersisted(true);  //设置设备重启后，是否重新执行任务
            if (mJobScheduler.schedule(builder.build()) <= JobScheduler.RESULT_FAILURE)
            {
                //If something goes wrong
                System.out.println("工作失败");
            } else {
                System.out.println("工作成功");
            }
        }
    }
    private void doJob()
    {
        if (!isServiceRunning(this, "com.qyy.remotemonitor.ui.service.RemoteMonitorService"))
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            {
                // 8.0 以上不允许后台service使用startService 启动服务
                startForegroundService(new Intent(this, RemoteMonitorService.class));

            }
            else
            {
                startService(new Intent(this, RemoteMonitorService.class));
            }
        }
    }



    @Override
    public boolean onStopJob(JobParameters params)
    {
        LogUtils.dTag("JobService","onStopJob");
        doJob();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            initSchedule();
        return true;
    }

    // 服务是否运行
    public boolean isServiceRunning(Context context, String serviceName) {
        boolean isRunning = false;
        ActivityManager am = (ActivityManager) this
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> lists = am.getRunningAppProcesses();


        for (ActivityManager.RunningAppProcessInfo info : lists) {// 获取运行服务再启动
            System.out.println(info.processName);
            if (info.processName.equals(serviceName)) {
                isRunning = true;
            }
        }
        return isRunning;

    }
}
